import os

from django.conf import settings

from utilities.email.my_email import EmailSender
from models.global_config import WebGlobalConfig
from apps.warn_center.serializer import FakeRequest
from utilities.djconsole import djconsole
from utilities.enums import PictureName
from wass.display import Picture


class WassEmailSender(EmailSender):
    encrypt_method_map = {0: None, 1: 'SSL', 2: 'TTL'}

    def __init__(self, authentication=None):
        email_settings = {}
        obj_global_config = WebGlobalConfig.objects.find_one()
        if obj_global_config:
            email_settings = obj_global_config.email_settings.to_dict()
        encrypt = email_settings.get('encrypt', 0)
        email = email_settings.get('email')
        password = email_settings.get('password')
        email_settings['sender'] = email

        if not authentication and email and password:
            authentication = (email, password)

        self.about = djconsole.get_license_detail(FakeRequest()).get('about', {})

        super(WassEmailSender, self).__init__(
            email_settings, authentication, method=self.encrypt_method_map.get(encrypt)
        )

    def send(self, template_name, args):
        """

        :param template_name:
        :param args:
        title:
        to: []
        body: {%k%: v}
        :return:
        """
        template_path = os.path.join(settings.STATIC_FOLDER, template_name)
        title_prefix = self.email_settings.get('email_prefix')
        if title_prefix:
            title_prefix = f"【{title_prefix}】"
        else:
            title_prefix = ""
        args['from'] = self.email_settings.get('sender')
        args['title'] = f"{title_prefix}{args['title']}"

        args['body']['%product_nickname_cn%'] = self.about.get('product_nickname_cn') or ''
        args['body']['%company_nickname_cn%'] = self.about.get('company_nickname_cn') or ''
        args['body']['%email_logo%'] = Picture().get_base64(PictureName.email_logo.value)
        args['body']['%div_connect_qr%'] = ""
        args['body']['%div_connect_tel%'] = ""

        if not settings.IS_OEM:
            args['body']['%div_connect_tel%'] = "<div>咨询电话：400-161-0866</div>"

            with open(os.path.join(os.path.dirname(__file__), 'connect_qr_div.html'), 'r', encoding='utf-8') as f:
                args['body']['%div_connect_qr%'] = f.read()

        super(WassEmailSender, self).send(template_path, args)
